package baseclass.z_lruCache;

import java.util.Iterator;
import java.util.LinkedList;

/**
 * 链表实现LRU
 * @date 2020/3/5 18:06
 */
public class Code01_LinkedLRUCache<K,V> {
    static class Node<K,V>{
        K k;
        V v;
        public Node(K k, V v) {
            this.k = k;
            this.v = v;
        }
    }
    private final int CAPACITY;
    private LinkedList<Node<K,V>> cache;

    public Code01_LinkedLRUCache(int CAPACITY) {
        this.CAPACITY = CAPACITY;
        cache = new LinkedList<>();
    }

    public void put(K k,V v){
        //1先检查K是否在cache中存在,如果存在则移除
        removeIfExist(k);
       //1.8自带 cache.removeIf(kvNode -> kvNode.k == k);
        //2如果不存在K，判断容量是否满了
        if(cache.size() >= CAPACITY){
            cache.removeLast();
        }
        //3把K,V添加到头部
        cache.addFirst(new Node<>(k,v));
    }
    public V get(K k){
        if(cache.size() == 0) return null;
        if(cache.getFirst().k == k) return cache.getFirst().v;
        //判断是否含有，如果含有，删除节点
        Node<K,V> node = removeIfExist(k);
        if(node == null) return null;
        //把节点移到first
        cache.addFirst(node);
        return node.v;
    }
    public V remove(K k){
        //判断是否含有，如果含有，删除节点
        Node<K,V> node = removeIfExist(k);
        return node == null ? null : node.v;
    }
    private Node removeIfExist(K k){
        Iterator<Node<K, V>> iterator = cache.iterator();
        while (iterator.hasNext()){
            Node<K, V> next = iterator.next();
            if(next.k == k){
                iterator.remove();
                return next;
            }
        }
        return null;
    }
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        Iterator<Node<K, V>> iterator = cache.iterator();
        while (iterator.hasNext()){
            Node node = iterator.next();
            sb.append("K：").append(node.k).append("  V:").append(node.v).append("\r\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Code01_LinkedLRUCache<Integer, String> cache = new Code01_LinkedLRUCache<>(5);
        for (int i = 1; i <= 5; i++) {
            cache.put(i," "+i);
            System.out.println(cache);
        }
        System.out.println("插入6");
        cache.put(6," "+6);
        System.out.println(cache);
        System.out.println("查询5");
        System.out.println(cache.get(5));
        System.out.println(cache);
        System.out.println("删除2");
        System.out.println(cache.remove(2));
        System.out.println(cache);
        System.out.println("插入2");
        cache.put(2,"2");
        System.out.println(cache);
        System.out.println("查询3");
        System.out.println(cache.get(3));
        System.out.println(cache);


    }

}
